﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Taobao.EF;
using Taobao.Manger;
using Taobao.Models;
using Taobao.Public;

namespace Taobao.Controllers
{
    [Taobao.Filter.CheckLogin(false)]
    public class LoginController : Controller
    {
        DbEntity db = new DbEntity();
        //
        // GET: /Login/

        public ActionResult Index()
        {

            return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 注册新用户
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="acount"></param>
        /// <param name="pwd"></param>
        /// <param name="repeatpwd"></param>
        /// <param name="regcode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RegisterUser(string userName, string acount, string pwd, string repeatpwd, string regcode)
        {
            JsonResult jr = new JsonResult();
            //非空校验 
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(acount) || string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(repeatpwd) || string.IsNullOrEmpty(regcode))
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.必填数据不能为空);
                return jr;
            }
            //校验手机号格式
            if (!ValidCode.CheckPhone(acount))
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.手机格式不正确);
                return jr;
            }
            //验证用户名是否重复
            var item = db.UseInfors.Where(o => o.userName == userName).FirstOrDefault();
            if (item != null)
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.用户名已经被注册);
                return jr;
            }

            //验证手机号是否注册
            item = db.UseInfors.Where(o => o.Account == acount).FirstOrDefault();
            if (item != null)
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.该手机号已经注册);
                return jr;
            }
            //校验密码一致性 
            if (pwd != repeatpwd)
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.两次密码不一致);
                return jr;
            }
            //验证码是否正确
            var ret = CheckCode(regcode, Constant.register);
            if (!ret)
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.验证码输入错误);
                return jr;
            }

            //保存数据库
            UseInfor uf = new UseInfor();
            uf.userName = userName;
            uf.Account = acount;
            uf.pwd = pwd;

            db.UseInfors.Add(uf);
            db.SaveChanges();

            jr = CustomClass.GetJsonRet(NoticeMsg.成功);
            return jr;
        }

        [HttpPost]

        public JsonResult Login(string userName, string pwd, string cacheCode)
        {
            HomeManger hm = new HomeManger();
            JsonResult jr = new JsonResult();
            BaseModel bm = new BaseModel();
            int total = 0;
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(cacheCode))
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.账号或密码不能为空);
                return jr;
            }
            // var inde = Convert.ToInt32(userName);
            //检验验证码
            var ret = CheckCode(cacheCode, Constant.cacheCode);
            if (!ret)
            {
                jr = CustomClass.GetJsonRet(NoticeMsg.验证码输入错误);
                return jr;
            }

            var item = db.UseInfors.Where(o => (o.Account == userName || o.userName == userName) && o.pwd == pwd);
            if (item != null && item.ToList().Count == 1)
            {
                SetCache(item.ToList()[0]);
                Session[Constant.cacheCode] = "";
                var reurnIem = CustomClass.GetCahce(Constant.returnUrl);
                string url = "";
                if (reurnIem != null)
                {
                    url = reurnIem.ToString();
                }
                CustomClass.RemoveCahce(Constant.returnUrl);
                //写缓存信息
                jr = CustomClass.GetJsonRet(NoticeMsg.成功, url);
                return jr;
            }
            jr = CustomClass.GetJsonRet(NoticeMsg.账号或密码错误);
            return jr;
        }
        /// <summary>
        /// 检验验证码是否正确
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool CheckCode(string code, string key)
        {
            var secode = Session[key];
            if (secode == null)
            {
                return false;
            }
            if (code != secode.ToString())
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 缓存用户信息
        /// </summary>
        /// <param name="userinfo"></param>
        public void SetCache(UseInfor userinfo)
        {
            HttpCookie nc = new HttpCookie(Constant.userInfo);
            nc.Values["name"] = HttpUtility.UrlEncode(userinfo.userName);
            nc.Values["pwd"] = "";
            nc.Values["userId"] = userinfo.UserId.ToString();
            //  nc.Values["Count"] = (userinfo.TotalCount + userinfo.SongCount).ToString();
            CustomClass.InsertCache(Constant.userInfo, userinfo, 0, 1);
            nc.Expires = DateTime.Now.AddMonths(1);
            Response.Cookies.Add(nc);
        }
        /// <summary>
        ///登录获取验证码
        /// </summary>
        /// <returns></returns> 
        public ActionResult GetValidataCode()
        {
            ValidCode vCode = new ValidCode();
            string code = vCode.CreateValidateCode(4);
            Session[Constant.cacheCode] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
        /// <summary>
        /// 注册  验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRegisterCode()
        {
            ValidCode vCode = new ValidCode();
            string code = vCode.CreateValidateCode(4);
            Session[Constant.register] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
        public ActionResult Out()
        {
            HttpCookie cok = Request.Cookies[Constant.userInfo];
            if (cok != null)
            {
                TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
                cok.Expires = DateTime.Now.Add(ts);


                //for(int index=0;index< Request.Cookies.Count;index++)
                //{
                //    Request.Cookies[index].Expires = DateTime.Now.AddDays(-20);
                //} 
                Response.AppendCookie(cok);
                CustomClass.RemoveCahce(Constant.userInfo);
            }


            return RedirectToAction("Index", "Login");
        }
    }
}